package com.bitters.springbootjpa;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * description:
 * author: thomashe
 * date: 2022/4/1
 */
public class DataStructure {

    public static void main(String[] args) {
        //testFindRepeatNumber();
        //testFindRepeatNumber2();
        System.out.println(testFindRepeatNumber4());
    }

    public static void testFindRepeatNumber() {
        Integer[] array = {2, 3, 4, 5, 6, 7, 3, 2, 4, 5, 3, 2};
        // one fun
        Set<Integer> set = new HashSet<Integer>();
        for (Integer a : array) {
            if (set.contains(a)) {
                System.out.println("發現重複的元的：" + a);
            } else {
                set.add(a);
            }
        }
    }

    //排序后查找
    public static int testFindRepeatNumber2() {
        Integer[] array = {2, 3, 4, 5, 6, 7, 3, 2, 4, 5, 3, 2};
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        for (int i = 1; i < array.length; i++) {
            Integer integer = array[i];
            if (array[i] == array[i - 1]) {
                System.out.println("重複的有：" + array[i]);
            }
        }
        System.out.println(Arrays.toString(array));
        return -1;
    }

    //排序后查找
    public static int testFindRepeatNumber3() {
        int[] array = {2, 3, 4, 5, 6, 7, 3, 2};
        int[] temp = new int[array.length];
        System.out.println("变化前的值为:" + Arrays.toString(temp));
        for (int i = 0; i < array.length; i++) {
            int nums = array[i];
            if (temp[nums] != 0) {
                System.out.println("重复的数字为:" + nums);
            }
            temp[nums] = 1;
        }
        System.out.println("变化后的值为:" + Arrays.toString(temp));
        return -1;
    }

    public static int testFindRepeatNumber4() {
        int[] nums = {2, 3, 4, 5, 6, 7, 3, 2};
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == i) { //索引等于本身
                continue;
            }
            int num = nums[i];
            if(nums[num]==num){
                System.out.println("当前的num已经存在"+num);
                return num;
            }
            int temp = nums[num];
            nums[num] = num;
            nums[i] = temp;
            i--;
            System.out.println(Arrays.toString(nums));
        }
        return -1;
    }


}
